package com.zxx.coolweather._wuguan2.queue_prority;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 没有顺序的队列
 *
 * @author zxx on 2022/1/12
 */
public class YolandaQueue {

    private BlockingQueue<Request> blockingQueue;
    private TaskExecutorMy[] taskExecutor;
    private AtomicInteger atomicInteger = new AtomicInteger();

    public YolandaQueue(int poolSize) {
        // 如果Comparable#compareTo(Object)方法不做比较返回0，那么是无序的
        blockingQueue = new PriorityBlockingQueue<>();
        taskExecutor = new TaskExecutorMy[poolSize];
    }

    public void add(Request request){
        request.setOrder(atomicInteger.incrementAndGet());
        blockingQueue.add(request);
    }

    public void start(){
        for (int i = 0; i < taskExecutor.length; i++) {
            taskExecutor[i] = new TaskExecutorMy(blockingQueue);
            taskExecutor[i].start();
        }
    }

    public void stop(){
        for (TaskExecutorMy taskExecutorMy : taskExecutor) {
            taskExecutorMy.setRunning(false);
            taskExecutorMy.interrupt();
        }
    }

}
